import * as vscode from 'vscode';
import { BugInfo, Configuration } from '../proto-gen';

import { ProjectBugApi } from '../proto-gen/api';
import { getProjectToken } from '../utils/tokenUtils';
import { unix } from 'moment';
import { getBasePath } from '../utils/basePathUtils';

export class MyBugProvider implements vscode.TreeDataProvider<BugItem> {
    private _onDidChangeTreeData: vscode.EventEmitter<BugItem | undefined | void> = new vscode.EventEmitter<BugItem | undefined | void>();
    readonly onDidChangeTreeData: vscode.Event<BugItem | undefined | void> = this._onDidChangeTreeData.event;


    getTreeItem(element: BugItem): vscode.TreeItem | Thenable<vscode.TreeItem> {
        return element;
    }
    getChildren(element?: BugItem | undefined): vscode.ProviderResult<BugItem[]> {
        if (element) {
            return [];
        } else {
            const basePath = getBasePath();
            if (basePath == null) {
                return [];
            }
            const api = new ProjectBugApi(new Configuration({
                basePath: basePath.basePath,
            }));
            const tokenInfo = getProjectToken();
            if (tokenInfo == null) {
                return [];
            }
            return new Promise<BugItem[]>((resolve, _) => {
                api.projectProjectIdBugMyGet(tokenInfo.projectId, basePath.token, "unclose").then(res => {
                    const result = res.data.map(item => new BugItem(item));
                    resolve(result);
                }).catch(e => {
                    console.log(e);
                    vscode.window.showErrorMessage(`${e}`);
                    resolve([]);
                });
            });
        }
    }
    sync() {
        this._onDidChangeTreeData.fire();
    }
}

export class BugItem extends vscode.TreeItem {
    constructor(bugInfo: BugInfo) {
        super(bugInfo.title ?? "");
        this.contextValue = 'bug';
        this.id = bugInfo.bugId;
        this.collapsibleState = vscode.TreeItemCollapsibleState.None;
        this.iconPath = new vscode.ThemeIcon("bug");
        const tooltip = `
- 状态: ${this.stateStr(bugInfo)}
- 创建者: ${bugInfo.createDisplayName ?? ""} 
- 执行者: ${bugInfo.execDisplayName ?? ""}
- 检查者: ${bugInfo.checkDisplayName ?? ""}
- 执行贡献: ${bugInfo.execAwardPoint ?? 0}
- 检查贡献: ${bugInfo.checkAwardPoint ?? 0}
- 软件版本: ${bugInfo.softwareVersion ?? ""}
- 缺陷级别: ${this.levelStr(bugInfo)}
- 优先级: ${this.priorityStr(bugInfo)}
- 创建时间: ${bugInfo.createTime == undefined ? "未知" : unix(bugInfo.createTime / 1000).format("YYYY-MM-DD HH:mm:ss")}
- 更新时间: ${bugInfo.updateTime == undefined ? "未知" : unix(bugInfo.updateTime / 1000).format("YYYY-MM-DD HH:mm:ss")}
        `;
        this.tooltip = new vscode.MarkdownString(tooltip);
    }

    private stateStr(bugInfo: BugInfo): string {
        if (bugInfo.state == undefined) {
            return "";
        }
        if (bugInfo.state == "plan") {
            return "规划中";
        } else if (bugInfo.state == "process") {
            return "处理中";
        } else if (bugInfo.state == "check") {
            return "检查中";
        } else if (bugInfo.state == "close") {
            return "已关闭"
        }
        return "";
    }

    private levelStr(bugInfo: BugInfo): string {
        if (bugInfo.level == undefined) {
            return "";
        }
        if (bugInfo.level == "minor") {
            return "提示";
        } else if (bugInfo.level == "major") {
            return "一般";
        } else if (bugInfo.level == "critical") {
            return "严重";
        } else if (bugInfo.level == "blocker") {
            return "致命";
        }
        return "";
    }

    private priorityStr(bugInfo: BugInfo): string {
        if (bugInfo.priority == undefined) {
            return "";
        }
        if (bugInfo.priority == "low") {
            return "低优先级";
        } else if (bugInfo.priority == "normal") {
            return "正常处理";
        } else if (bugInfo.priority == "high") {
            return "高度重视";
        } else if (bugInfo.priority == "urgent") {
            return "急需解决";
        } else if (bugInfo.priority == "immediate") {
            return "马上解决";
        }
        return "";
    }

    async show(): Promise<void> {
        const basePath = getBasePath();
        if (basePath == null) {
            return;
        }
        const api = new ProjectBugApi(new Configuration({
            basePath: basePath.basePath,
        }));
        const tokenInfo = getProjectToken();
        if (tokenInfo == null) {
            return;
        }
        await api.projectProjectIdBugRecordBugIdShowGet(tokenInfo.projectId, this.id ?? "", basePath.token);
    }

    async shortNote(): Promise<void> {
        const basePath = getBasePath();
        if (basePath == null) {
            return;
        }
        const api = new ProjectBugApi(new Configuration({
            basePath: basePath.basePath,
        }));
        const tokenInfo = getProjectToken();
        if (tokenInfo == null) {
            return;
        }
        await api.projectProjectIdBugRecordBugIdShortNoteGet(tokenInfo.projectId, this.id ?? "", basePath.token);
    }
}